/**
 * @author HuangWenJing
 */

function disableWidthCondtion(sel, refer, values) {
	var $sel = $(sel), $refer = $(refer);
	var referVal = $refer.val();
	for ( var i in values) {
		var value = values[i];
		if (referVal === value) {
			$(sel).combobox('setOption', {
				disabled : true
			});
			return;
		}
	}

	$(sel).combobox('setOption', {
		disabled : false
	});
};

(function() {

	$.select = {
		cache : {}, // cache是缓存下拉框的变量，key:下拉框的name属性，value:下拉框的option字符串
		readyList : [],
		handler : function(sel, codes, result) {
			var str = '';
			if (codes && result) {
				for ( var i in codes) {
					var value = codes[i];
					var text = result[value];
					str += '<option value="' + value + '">' + text
							+ '</option>';
				}
			}

			$(sel).append(str);
		},
		addOption : function(value, text) {
			return $('<option value="' + value + '">' + text + '</option>');
		},
		/**
		 * 初始化多个下拉框
		 * 
		 * @param configs
		 *            下拉框配置列表， 结构：参考selReady函数的defOpt变量
		 * @param paraMap
		 *            参数列表(ID)，此参数是树形结构传来的ID值，不需要可设为null
		 * @param paraNameMap
		 *            参数名列表(NAME)此参数是树形结构传来的NAME值，不需要可设为null
		 * @param callBack
		 *            回调函数
		 */
		initSels : function(configs, paraMap, paraNameMap, callBack) {

			var list = [];
			paraNameMap = paraNameMap || {}, paraMap = paraMap || {};

			for ( var i = 0; i < configs.length; i++) {
				var config = configs[i];
				var element = config.element, $el = $(element);
				var id = $el.attr('id');

				if (paraMap[id] && paraNameMap[id]) {
					var value = paraMap[id], text = paraNameMap[id];
					var option = this.addOption(value, text);
					$el.append(option);
					this.setSelDefault(id);
				} else {
					var temp = $el.selReady(config);
					list = list.concat(temp);
				}
			}
			this.load(paraMap, callBack, list);
		},
		/**
		 * 刷新多个下拉框
		 * 
		 * @param elements
		 *            元素列表 结构：参考selReady函数的defOpt变量
		 * @param paraMap
		 *            参数列表(ID)
		 * 
		 * @param callBack
		 *            回调函数
		 */
		refresh : function(elements, paraMap, callBack) {// 重载下拉框
			// 清空cache变量
		this.cache = {};
		var list = [];

		for ( var i in elements) {
			var element = elements[i];
			$(element).each(function() {
				var option = $(this).getSelOption();
				list.push(option);
			});
		}
		this.load(paraMap, callBack, list);
	},
	/**
	 * 加载多个下拉框主要函数
	 * 
	 * @param paraMap
	 *            参数列表(ID)
	 * 
	 * @param complete
	 *            回调函数
	 * @param list
	 *            下拉框配置的列表
	 */
	load : function(paraMap, complete, list) {

		var readyList = list || this.readyList;
		paraMap = paraMap || {};
		for ( var i = 0; i < readyList.length; i++) {
			// 在回调中加载select数据
		(function() {
			var ii = i;
			var opt = readyList[ii];

			// if (paraMap[opt.elId]) {
		// opt.defLabel.enable = false;
		// }

		opt.load = function(data) {

			if (ii < readyList.length - 1) {
				var next = readyList[ii + 1];
				getSelect(next, paraMap);
			} else if ($.isFunction(complete)) {// 当所有的下拉框都加载完成，进行下一步
				complete();
				complete = null;
			}

		};
	})();
}

if (readyList.length > 0) {
	var first = readyList[0];
	getSelect(first, paraMap);
} else {
	if ($.isFunction(complete)) {
		complete();
		complete = null;
	}
}
},
setSelDefault : function(id, value) {// 设置默认值
			var sel = $('#' + id);
			var selValue = value || $('#' + id + ' option:first').attr('value');

			sel.combobox('setOption', {
				value : selValue
			});
		},
		/**
		 * 下拉框选中后刷新报表
		 * 
		 * @param opt
		 *            选项配置
		 * @param e
		 * @param ui
		 * @param selId
		 *            下拉框ID
		 */
		onSelect : function(opt, e, ui, selId) {
			opt = opt || {};
			e = e || {};
			ui = ui || {};

			var data = getParams(opt.data, opt.masters);
			if (opt.formId) {
				data = getFormData(opt.formId);
			}

			if (!selId) {
				return;
			}
			var rootEl = $.utils.getChartRootEL(selId);

			// 获取报表内的查询条件
		var chartFormData = {};
		var chartForm = $(rootEl).find("form");
		if (chartForm) {
			chartFormData = $.utils.formArrayToObj($(chartForm).find(
					'*[allowserialize!="no"]'));
		}
		data = $.extend(true, data, chartFormData);

		// 刷新报表
		var gridEl = $(rootEl).find(".grid");
		var chartEl = $(rootEl).find(".chart");
		var isFlowProgress = $("#" + selId).attr("isFlowProgress");

		if (isFlowProgress) { // 刷新流程图
			var divArray = $.find(".page-content div[dynDiv=true]"); // 获得所有需要动态加载的DIV
			for ( var i = 0; i < divArray.length; i++) {
				var moduleCode = $(divArray[i]).attr("moduleCode");
				var reqUrl = $(divArray[i]).attr("reqUrl");

				$("#div_" + moduleCode).showLoading( {
					"parent" : "#div_" + moduleCode
				}).load(jsContextPath + reqUrl, data, function() {
					$(this).hideLoading();
					if ($(".programTree").length > 0) {
						$(".programTree").flowProgress();
					}
				});

			}
			return;
		}

		if (0 < chartEl.length) { // 刷新fusionchart
			$.utils.updateChartAll(chartEl, {
				params : data
			});
		}

		if (0 < gridEl.length) { // 刷新jqgrid
			$(gridEl).each(function() {
				$(this).jqGrid('setGridConfig', {
					paramObj : data
				});
				$(this).doFind();
			});
		}
	}
	};

	/**
	 * 后台获取下拉框数据
	 * 
	 * @param opt
	 *            下拉框的配置
	 */
	$.fn.select = function(opt) {
		opt = opt || {};

		this.each(function() {
			var sel = this, selName = sel.name;
			var cache = $.select.cache;
			var init = true;

			if (opt.cacheable) {// 如果设置有缓存
					var item = getCache(opt, selName);
					if (item) {// 在cache变量里是否找到该下拉框的缓存，有缓存就不需要去后台加载数据
						init = false;
						$(sel).empty();
						// append缓存值
						$(sel).append(item);
						$.select.setSelDefault(opt.elId);
						if ($.isFunction(opt.load)) {
							opt.load.call(sel);
						}
					}
				}

				var data = $.extend(true, {}, opt.data);

				if (opt.formId && opt.formData) {
					for ( var i in opt.formData) {
						data[i] = opt.formData[i];
					}
				}

				if (init) {
					$.ajax( {
						url : opt.url,
						type : 'post',
						data : data,
						dataType : 'json',
						success : function(data, stauts, XHR) {

							// 先清空下拉框
						$(sel).empty();
						var defLabel = opt.defLabel;
						if (defLabel.enable) {
							var firstLabel = $.select.addOption(defLabel.code,
									defLabel.value);
							$(sel).append(firstLabel);
						}

						if (data) {
							var selectBean = data.selectBean;
							var userData = selectBean.userData || {};
							var error = userData.error;
							if (!error) {
								$.select.handler(sel, selectBean.codes,
										selectBean.result);
							}
						}

						if (defLabel.code) {
							$.select.setSelDefault(opt.elId, defLabel.code);
						} else {
							$.select.setSelDefault(opt.elId);
						}

						if (opt.cacheable) {// 将下拉框的option缓存起来
							setCache(opt, selName, $(sel).html());
						}

						if ($.isFunction(opt.load)) {
							opt.load.call(sel, data);
						}

						if ($.isFunction(opt.callBack)) {
							opt.callBack.call(sel, data);
						}
					}
					});
				}

			});

	};

	$.fn.extend( {
		/**
		 * 获取下拉框配置
		 */
		getSelOption : function() {
			return $(this)[0].selOpt || {};
		},
		/**
		 * 刷新下拉框
		 */
		refreshSel : function() {
			this.each(function() {
				var opt = $(this).getSelOption();
				var data = getParams(opt.data, opt.masters);
				if (opt.formId) {
					data = getFormData(opt.formId);
				}
				getSelect(opt, data);
			});
		},
		/**
		 * 设置下拉框配置，加载下拉框前的操作，包括缓存配置、联动设置等
		 * 
		 * @param opt
		 *            下拉框的配置，带有默认值
		 */
		selReady : function(opt) {
			var list = [];
			this.each(function() {
				var sel = this;
				var id = sel.id;

				if (!id) {
					alert('请设置下拉框id');
					return;
				}

				// 默认配置
					var defOpt = {
						element : '',
						basePath : '',
						url : '/select/getSelect.do',
						reportId : null,
						formId : null,
						data : {},
						formData : {},
						masters : [],
						chartId : [],
						defLabel : {
							enable : true,
							code : '',
							value : '所有'
						},
						refreshFrame : {
							enable : false,
							handler : $.select.refreshFrame
						},
						refreshChart : { // 刷新报表
							enable : false,
							handler : $.select.onSelect
						},
						cacheable : false,// 是否做缓存
						callBack : null,
						load : null,
						width : null
					};

					defOpt = $.extend(true, defOpt, opt || {});

					// 设置下拉框的宽度
					if (defOpt.width) {
						var span = $(sel).next();
						var input = $(span).find('input');
						input.width(defOpt.width);
					}

					if (!defOpt.reportId) {
						// alert('请配置ibatis id');
						return;
					}

					defOpt.basePath = jsContextPath || defOpt.basePath;
					defOpt.url = defOpt.basePath + defOpt.url;

					var masters = $(sel).attr('masters') || '';

					masters = masters.split(';');
					defOpt.masters = masters;

					defOpt.data.reportId = defOpt.reportId;
					defOpt.elId = id;

					var refreshFrame = defOpt.refreshFrame;
					if (refreshFrame.enable) {
						// refreshFrame.handler();
						$(sel).attr('change', 'true');
					}

					/*
					 * $(sel).combobox('getInput').on('autocompleteselect',
					 * function( event, ui ) { var item = ui.item; var select =
					 * $(item).parent(); linkage(select); } );
					 */

					var refreshChart = defOpt.refreshChart;
					$(sel).combobox( {
						select : function(evt, ui) {
							var item = ui.item;
							var select = $(item).parent();
							// linkage(select);
							$.utils.widgetLinkage(select);

							// TODO
							// 报表中的下拉框选中后刷新此报表
							if (refreshChart.enable) {
								var selId = $(select).attr("id");
								if (selId) {
									var selOpt = $(this).getSelOption();
									refreshChart
											.handler(selOpt, evt, ui, selId);
								}
							}
						}
					});

					// 将配置缓存起来
					sel.selOpt = defOpt;
					list.push(defOpt);
				});

			return list;
		}
	});

	/**
	 * 获取下拉框值，将此函数包起来，不允许外部对其进行修改
	 * 
	 * @param opt
	 *            下拉框的配置
	 * @param paraMap
	 *            参数列表(ID)
	 */
	function getSelect(opt, paraMap) {
		var data = paraMap || {};

		if (opt.formId) {
			opt.formData = getFormData(opt.formId);
			$.extend(data, paraMap);
		}
		$.extend(opt.data, data);

		if (opt.masters && opt.masters.length > 0) {
			getParams(opt.data, opt.masters);
		}
		$('#' + opt.elId).select(opt);
	}
	;

	function getParams(map, list) {
		for ( var i in list) {
			var item = list[i];
			var name = $('#' + item).attr('name');
			var value = $('#' + item).val();
			map[name] = value;
		}
	}
	;

	/**
	 * form转map
	 * 
	 * @param formId
	 *            form的ID
	 * 
	 * @return data
	 */
	function getFormData(formId) {
		var data = $.utils.formArrayToObj($('#' + formId).find(
				'*[allowserialize!="no"]'));
		return data;
	}
	;

	function getCacheName(masters, elName) {
		var index = elName;
		for ( var i in masters) {
			var master = masters[i];
			var value = $('#' + master).val();
			if (value) {
				index += '_' + value;
			}
		}
		return index;
	}
	;

	/**
	 * 获取下拉框缓存
	 * 
	 * @param opt
	 *            下拉框的配置
	 * @param elName
	 *            下拉框的name属性
	 * @return item
	 */
	function getCache(opt, elName) {
		var masters = opt.masters;
		var index = getCacheName(masters, elName);
		var cache = $.select.cache, item = cache[index];
		return item;
	}
	;

	/**
	 * 下拉框设置缓存
	 * 
	 * @param opt
	 *            下拉框的配置
	 * @param elName
	 *            下拉框的name属性
	 * @param obj
	 *            要缓存的值
	 */
	function setCache(opt, elName, obj) {
		var masters = opt.masters;
		var index = getCacheName(masters, elName);
		var cache = $.select.cache;
		cache[index] = obj;
	}
	;
})();
